import Vue from 'vue'
import Router from 'vue-router'
import { checkPermission } from '@/common/utils/permission.js'

import i18n from '../common/i18n'

Vue.use(Router)

const defaultRoutes = [
  {
    path: '/login',
    component: (resolve) => require(['@/views/login/login'], resolve),
    hidden: true
  },
  {
    path: '/',
    component: (resolve) => require(['@/views/login/login'], resolve),
    hidden: true
  },
  {
    path: '/404',
    component: (resolve) => require(['@/views/error/404'], resolve),
    hidden: true
  },
  {
    path: '/401',
    component: (resolve) => require(['@/views/error/401'], resolve),
    hidden: true
  },
]

//解决ElementUI导航中的重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push(location){
  return originalPush.call(this,location).catch(err=>err)
}

import SysSettingRoutes from './module/system_setting'
const routes = new Set([...defaultRoutes,...SysSettingRoutes])

const router = new Router({
  //mode: 'history',
  base: process.env.BASE_URL,     //配置单页应用的基础路径
  routes
})

const whiteRouter = ['/','/login','/401','/404']
//路由拦截  需要校验权限问题   后期直接从后台回去路由配置动态添加则无须校验
router.beforeEach(async (to, from, next) => {
  // console.log(to.path)

  // console.log('用户信息存贮',to,from,next)
  if (to.meta.title) {
    document.title = i18n.t(to.meta.title) //to.meta.title
  }
  if(whiteRouter.indexOf(to.path) != -1){
    next()
  }else{
    if(to.meta.code != null && to.meta.code != ''){     //表示需要校验权限
      const permissions = JSON.parse(sessionStorage.getItem('permissionsList'))
      if(permissions != null && permissions.length > 0){
        if(!checkPermission(to.meta.code)){
          next({
            path:'/401'
          })
        }else{
          next()
        }
      }else{
        next({
          path:'/401'
        })
      }
      return
    }else{
      next({
        path:'/401'
      })
    }
  }

})

export default router
